/**
 * Assistant Store - 助手状态管理
 * 
 * Features:
 * - Manage assistants list
 * - Track selected assistant
 * - Manage favorites
 * - Track recent usage
 * - Persist preferences to localStorage
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export interface Assistant {
  id: string;
  name: string;
  description: string;
  prompt?: string;
  tools?: string[];
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
  skillIds?: string[];
  category?: string;
  tags?: string[];
  isBuiltin?: boolean;
  isFavorite?: boolean;
  lastUsed?: number;
  icon?: string; // Icon name from lucide-react or emoji
  iconColor?: string; // Custom color for icon background
}

interface AssistantStore {
  // State
  assistants: Assistant[];
  selectedAssistant: Assistant | null;
  favoriteIds: string[];
  recentIds: string[];
  loading: boolean;
  error: string | null;

  // Actions
  fetchAssistants: () => Promise<void>;
  selectAssistant: (id: string | null) => void;
  toggleFavorite: (id: string) => void;
  addToRecent: (id: string) => void;
  clearRecent: () => void;
  setAssistants: (assistants: Assistant[]) => void;
  getAssistantById: (id: string) => Assistant | undefined;
}

export const useAssistantStore = create<AssistantStore>()(
  persist(
    (set, get) => ({
      // Initial State
      assistants: [],
      selectedAssistant: null,
      favoriteIds: [],
      recentIds: [],
      loading: false,
      error: null,

      // Fetch assistants from API
      fetchAssistants: async () => {
        set({ loading: true, error: null });
        try {
          const response = await fetch('http://localhost:3000/api/subagents');
          const data = await response.json();
          
          if (data.success) {
            const assistantsData = data.data.subagents || [];
            const { favoriteIds, recentIds } = get();
            
            // Enrich assistants with favorite and lastUsed info
            const enrichedAssistants = assistantsData.map((a: Assistant) => ({
              ...a,
              isFavorite: favoriteIds.includes(a.id),
              lastUsed: recentIds.indexOf(a.id) >= 0 
                ? Date.now() - recentIds.indexOf(a.id) * 60000 // Approximate time
                : undefined,
            }));
            
            set({ 
              assistants: enrichedAssistants,
              loading: false,
            });
          } else {
            set({ 
              error: 'Failed to fetch assistants',
              loading: false,
            });
          }
        } catch (error) {
          console.error('Failed to fetch assistants:', error);
          set({ 
            error: error instanceof Error ? error.message : 'Unknown error',
            loading: false,
          });
        }
      },

      // Select an assistant
      selectAssistant: (id: string | null) => {
        const { assistants, addToRecent } = get();

        if (id === null) {
          set({ selectedAssistant: null });
          return;
        }

        const assistant = assistants.find(a => a.id === id);
        if (assistant) {
          set({ selectedAssistant: assistant });
          addToRecent(id);
        }
      },

      // Toggle favorite status
      toggleFavorite: (id: string) => {
        set((state) => {
          const isFavorite = state.favoriteIds.includes(id);
          const newFavoriteIds = isFavorite
            ? state.favoriteIds.filter(fid => fid !== id)
            : [...state.favoriteIds, id];

          // Update assistants list
          const updatedAssistants = state.assistants.map(a =>
            a.id === id ? { ...a, isFavorite: !isFavorite } : a
          );

          return {
            favoriteIds: newFavoriteIds,
            assistants: updatedAssistants,
          };
        });
      },

      // Add to recent list
      addToRecent: (id: string) => {
        set((state) => {
          // Remove if already exists
          const filtered = state.recentIds.filter(rid => rid !== id);
          // Add to front, keep max 10
          const newRecentIds = [id, ...filtered].slice(0, 10);

          // Update assistants list with new lastUsed
          const updatedAssistants = state.assistants.map(a => {
            const recentIndex = newRecentIds.indexOf(a.id);
            return {
              ...a,
              lastUsed: recentIndex >= 0 
                ? Date.now() - recentIndex * 60000 
                : a.lastUsed,
            };
          });

          return {
            recentIds: newRecentIds,
            assistants: updatedAssistants,
          };
        });
      },

      // Clear recent list
      clearRecent: () => {
        set((state) => ({
          recentIds: [],
          assistants: state.assistants.map(a => ({
            ...a,
            lastUsed: undefined,
          })),
        }));
      },

      // Set assistants (for manual updates)
      setAssistants: (assistants: Assistant[]) => {
        set({ assistants });
      },

      // Get assistant by ID
      getAssistantById: (id: string) => {
        return get().assistants.find(a => a.id === id);
      },
    }),
    {
      name: 'assistant-storage', // localStorage key
      partialize: (state) => ({
        // Only persist these fields
        favoriteIds: state.favoriteIds,
        recentIds: state.recentIds,
        selectedAssistant: state.selectedAssistant,
      }),
    }
  )
);

// Selectors for common queries
export const selectFavoriteAssistants = (state: AssistantStore) =>
  state.assistants.filter(a => a.isFavorite);

export const selectRecentAssistants = (state: AssistantStore) =>
  state.assistants
    .filter(a => a.lastUsed !== undefined)
    .sort((a, b) => (b.lastUsed || 0) - (a.lastUsed || 0));

export const selectAssistantsByCategory = (state: AssistantStore, category: string) =>
  state.assistants.filter(a => a.category === category);

export const selectBuiltinAssistants = (state: AssistantStore) =>
  state.assistants.filter(a => a.isBuiltin);

export const selectCustomAssistants = (state: AssistantStore) =>
  state.assistants.filter(a => !a.isBuiltin);

